<template>
    <div class="address-list" v-show="hasIconData">
      <div class="tree-wrap">
        <div class="search-ctrl f-l" >
          <input type="text" class="search-text query-msm-search"
                 v-model="searchStr"
                 placeholder="搜索部门名称或警员姓名">
          <button type="button"
                  @click="searchBtn"
                  style="right: 46px;"
                  class="search-btn btn btn-info" >搜索</button>
          <button type="button"
                  @click="clearSearBtn"
                  class="search-btn btn btn-info" >清空</button>
        </div>
        <div id="tree-dep" class="ztree div-tree"></div>
      </div>
        <!-- {{TreeNodes}} -->
      <div class="content-wrap Btns-ctrl-body">
        <div class="btns f-r">
          <button type="button"
                  class="btn btn-info"
                  @click="btnAddDepartment"
                  v-show="isDepartment">
            新增下级部门
          </button>
          <button type="button"
                  class="btn btn-warning"
                  @click="btnUpdataDepartment"
                  v-show="isDepartment">
            修改部门
          </button>
         <!-- <button type="button"
                  class="btn btn-warning"
                  @click="updataAddressPeopleFn"
                  v-show="!isDepartment">
            修改警员信息
          </button>-->
          <button type="button"
                  class="btn btn-danger"
                  @click="btnDeleteDepartment"
                  v-show="isDepartment">
            删除部门
          </button>
          <button type="button"
                  class="btn btn-info"
                  @click="btnAddPolice('findAllPolice')"
                  v-show="isDepartment">
            从全部警员中添加到通讯录
          </button>
          <!-- 从归属部门警员中添加通讯录-->
          <button type="button"
                  class="btn btn-info"
                  @click="btnAddPolice('findPoliceByStationId')"
                  v-show="isDepartment">
            从归属部门警员中添加到通讯录
          </button>
          <button type="button"
                  class="btn btn-danger"
                  @click="deleteRalationBatch"
                  v-show="isDepartment">
            通讯录中移除
          </button>
        </div>
        <div class="click-wrap">
          <!--require('@/../static/img/department.png')-->
          <img class="title-img" :src="require('@/../static/img/bg_addressList.jpg')" alt="">
          <div class="title-wrap">
            <div class="user-wrap">
              <div class="user-img-wrap">
                <img class="user-img" :src="userImgSrc" alt="">
              </div>
              <div class="user-name" v-text="userName" ></div>
            </div>
          </div>
          <div class="details-wrap">
            <div class="details-department" v-show="isDepartment">
              <div class="department-wrap">
                <span class="department-title">电话：</span>
                <span class="department-content" v-text="stationTel"></span>
              </div>
              <div class="department-wrap">
                <span class="department-title">手台：</span>
                <span class="department-content" v-text="stationRadioId"></span>
              </div>
            </div>
            <div class="details-department" v-show="!isDepartment">
              <div class="department-wrap">
                <span class="department-title">单位：</span>
                <span class="department-content" v-text="policeDepartment"></span>
              </div>
              <div class="department-wrap">
                <span class="department-title">手台：</span>
                <span class="department-content" v-text="policeRadioId"></span>
              </div>
              <div class="department-wrap">
                <span class="department-title">电话：</span>
                <span class="department-content" v-text="policePhone"></span>
              </div>
              <div class="department-wrap">
                <span class="department-title">职位：</span>
                <span class="department-content" v-text="policePosition"></span>
              </div>
            </div>
          </div>
        </div>
        <tableMate
            class="table-mate-height"
            v-show="allDataSum && isDepartment"
            :header-table="headerTable"
            :table-data="addressPageList"
            :clearCheckedAry="clearCheckedAry"
            @checkedAryFn="checkedAryFn"
            @updataAddressFn="updataAddressFn"
        ></tableMate>
        <!-- 分页 -->
        <pages class="pages"
               v-show="allDataSum && isDepartment"
               :showItem = showItem
               :allpage = allpage
               :pageSize = pageSize
               :allDataSum = allDataSum
               @current-change = currentChange >
        </pages>
        <!-- 分页闭合 -->
      </div>
      <!-- 新增部门 -->
      <addDepartmentModal :AddDepartmentModalObj="AddDepartmentModalObj"
                          @addDepartmentClose="addDepartmentClose"
      >
      </addDepartmentModal>
      <!-- 新增部门end -->
      <!-- 新增通讯录人员 -->
      <addPoliceModal
          :table-mate-data="addressPageList"
          :AddPoliceModalObj="AddPoliceModalObj"
          @addPoliceClose="addPoliceClose"
      >
      </addPoliceModal>
      <!-- 新增通讯录人员end -->
      <!-- 修改部门 -->
      <updateDepartmentModal
        :updateDepartmentModalObj="updateDepartmentModalObj"
        @updateDepartmentClose="updateDepartmentClose"
      >
      </updateDepartmentModal>
      <!-- 修改部门end -->
      <!-- 通讯录人员信息修改 -->
      <updateAddressPeopleModal
      :updateAddressPeopleModalObj="updateAddressPeopleModalObj"
      @updateAddressPeopleModalClose="updateAddressPeopleModalClose"
    >
    </updateAddressPeopleModal>

    </div>
</template>

<script>
  import addDepartmentModal from "./addDepartmentModal";
  import updateDepartmentModal from "./updateDepartmentModal";
  import tableMate from "./tableMate";
  import addPoliceModal from "./addPoliceModal";
  import updateAddressPeopleModal from "./updateAddressPeopleModal";
  import pages from '@/components/sudoku/atom/pages';
  export default {
    name: "addressAdmin",
    data(){
      return {
        // 树初始化的配置
        setting : {
          data: {
            simpleData: {
              enable: true
            },
          },
          view: {
            // showIcon: this.showIconForTree
            showIcon: false
          },
          /*async: {
            enable: true,
            url: baseURL+'api/jp-HCZZ-AdminWeb-app-ms/addressbook/updatemaillist/findstationandpolice',
            autoParam: ["id"],
            type: "get",
            dataFilter: this.ajaxDataFilter
          },*/
          callback: {
            onClick: this.zTreeOnClick,
            onExpand: this.zTreeOnExpand
          }
        },
        hasIconData: null, // 渲染树的数据
        userImgSrc: '',   // 图片地址
        userName: '',    // 图片旁边对应名称
        stationRadioId: '',  // 部门的手台
        stationTel: '',  // 部门的电话
        isDepartment: false, // 点击的是否是部门
        policePhone: '', // 点击人员电话
        policeRadioId: '', // 点击人员手台
        policePosition: '', // 点击人员职位
        policeDepartment: '', // 点击人员单位
        type: 0,  // 0 虚拟部门 1 实际部门
        // 新增部门弹窗数据
        AddDepartmentModalObj: {  // 新增部门弹窗
          isShow: false,
          partParentId: ''
        },
        // 新增警员到通讯录
        AddPoliceModalObj: {  // 新增警员到通讯录弹窗
          isShow: false,
          partId: '',         // 查询警员使用的id
          btnType: '',        // 点击的按钮是全部（findAllPolice）还是归属部门（findPoliceByStationId）
          stationId: ''       // 添加警员到对应部门的部门id
        },
        // 修改部门弹窗数据
        updateDepartmentModalObj: { // 修改部门弹窗
          isShow: false,
          id: '',
          partParentId: '',
          partName: '',
          partTel: '',
          partRadioId: '',
          sort: 0,
          type: 0
        },
        realDepartmentId: '',   // 搜索
        addressPageList: [],    // 通讯录人员分页数据
        clearCheckedAry: false,
        addressPageTotal: null, // 通讯录人员分页数据总条数
        headerTable: [
          { "name" : "姓名" },
          { "name" : "电话" },
          { "name" : "手台" },
          {"name" : "职位" },
          {"name" : "排序" },
          {"name" : "加密" }
        ],        // 通讯录人员显示
        checkedAddressAry: [],  // 通讯录列表被点击的项
        stationId: '',          // 点击部门的id
        // 通讯录人员信息修改弹窗
        updateAddressPeopleModalObj: {
          isShow: false,
          policeGuid: '',         // 警员id
          policePhone: '',      // 警员的电话 ,
          policePosition : '',  // 警员的职务id ,
          policeRadioId : '',   // 手台 ,
          sort: 0,              // sort
        },
        treeNode: null,

        showItem: 10,       //分页条下面item的数目
        allpage: 0,         //根据每页数据/总数据得到的总页数
        pageSize: 20,       //每页数据
        allDataSum: 0,      //总数据
        cur: 1,
        searchStr: '',

      }
    },
    computed:{

    },
    components: {
      addDepartmentModal,
      updateDepartmentModal,
      tableMate,
      addPoliceModal,
      updateAddressPeopleModal,
      pages
    },
    mounted(){
     this.init();
    },
    methods: {
      init(){
        //初始化加载树结构
        let params = {};
        this.treeAjax( baseURL+'api/jp-BIRM-UserProfile-ms/addressbook/maillist/findalldata','get',params);
        // this.initTable();
      },
      // 搜索框搜索事件
      searchBtn(){
        if(this.searchStr.length>0){
          this.treeAjax(baseURL+'api/jp-BIRM-UserProfile-ms/addressbook/search/findbykeywords?keyWord='+this.searchStr,"get")
        }else {
          this.treeAjax(baseURL+'api/jp-BIRM-UserProfile-ms/addressbook/maillist/findalldata','get');
        }
      },
      // 搜索框清除事件
      clearSearBtn(){
        this.searchStr = '';
        this.treeAjax(baseURL+'api/jp-BIRM-UserProfile-ms/addressbook/maillist/findalldata','get');
      },
      //树结构加载
      treeAjax(url,type,params){
        this.s_loading(true)
        this.$axios[type](url)
          .then((data)=>{
            // let tepData = this.switchData(data.data);
            let tepData = data.data;
            this.hasIconData = this.addPeopelNumAfterStationName(tepData);
            $.fn.zTree.init($("#tree-dep"), this.setting, this.hasIconData);
            $(function(){
              $("#tree-dep > li").eq(0).children("a").click();
            });
            this.$nextTick(()=>{
              this.setBackSize();
            })
            this.s_loading(false)
          })
          .catch((err)=>{
            this.s_loading(false)
            this.s_alert('树形结构数据加载错误')
            //console.log(err);
          })
      },
      // 为树增加警员的图片地址
      showIconForTree(treeId, treeNode){
        // 如果有pictureUrl则代表是人员，以图标的方式显示图像
        return treeNode.hasOwnProperty('pictureUrl');
      },
      // 当树的某项被点击
      zTreeOnClick(evt, treeId, treeNode){
        if(treeNode.hasOwnProperty('policeCode')){  // 点击的是人员
          this.userImgSrc = treeNode.icon;
          this.isDepartment = false;
           // policePhone: '', // 点击人员电话
           //  policeRadioId: '', // 点击人员手台
           //  policePosition: '', // 点击人员职位
           //  policeDepartment: '', // 点击人员单位
          this.StringIf(treeNode, 'policePhone' )
          this.StringIf(treeNode, 'policeRadioId' )
          this.StringIf(treeNode, 'policePosition' )
          let parentAry = treeNode.getPath();
          let str = '';
          for(let i = 0; i < parentAry.length-1; i++){
            str = str + parentAry[i]['name']
          }
          this.$axios.get(baseURL + 'api/jp-BIRM-UserProfile-ms/addressbook/mail/findnamebyid?partId=' + treeNode.pId).then(res => {
            this.policeDepartment = res.data;
          }).catch(err => {
            this.policeDepartment = '部门名称查询失败'
            console.log(err, '通讯录pid查部门名称')
          })
        }
        else {  // 点击部门
          this.userImgSrc = require('@/../static/img/department.png');
          this.isDepartment = true;
          this.type = treeNode.type;
          // 点击的是虚拟部门寻找到最近的真实部门的id
          if(this.type === 0){
            // 传递查询部门警员的id
            this.AddPoliceModalObj.partId = this.searchRealDepartmentId(treeNode.getPath());
          }
          // 点击的是真实部门
          else if(this.type === 1){
            this.AddPoliceModalObj.partId = treeNode.id;
          }
          this.AddPoliceModalObj.stationId = treeNode.id;
          this.stationId = treeNode.id;
          this.initTable()
          // 初始化弹窗数据
          // 新增弹窗id作为新增部门pId
          this.AddDepartmentModalObj.partParentId = treeNode.id;
          //
          // 修改弹窗
          this.updateDepartmentModalObj.id = treeNode.id;                 //本身id

          /*this.updateDepartmentModalObj.partName = treeNode.name;         // 名称
          this.updateDepartmentModalObj.partParentId = treeNode.pId;      // 父级id
          this.updateDepartmentModalObj.partRadioId = treeNode.stationRadioId;      // 手台
          this.updateDepartmentModalObj.partTel = treeNode.stationTel;    // 电话
          this.updateDepartmentModalObj.sort = treeNode.sort;    // 排序
          this.updateDepartmentModalObj.type = treeNode.type; // 0 虚拟部门 | 1 实部门*/
          // 初始化弹窗数据end

          // 如果stationRadioId（手台）和stationTel（电话）为空则显示暂无
          if(treeNode.stationRadioId){
            this.stationRadioId = treeNode.stationRadioId;
          }
          else {
            this.stationRadioId = '暂无';
          }
          if(treeNode.stationTel){
            this.stationTel = treeNode.stationTel;
          }
          else {
            this.stationTel = '暂无';
          }

        }
        // 部门名称或者人员名称
        this.userName = treeNode.name;
        // 初始化table
        this.initTable();
        //
        this.treeNode = treeNode;
        //console.log(evt)
        //console.log(treeId)
        //console.log(JSON.stringify(treeNode))
        //console.log(this.isDepartment)
      },
      // 初始化table
      initTable(){
        //显示对应部门的通讯录人员
        this.axiosAddressPageListFn();
      },
      axiosAddressPageListFn(){
        //显示对应部门的通讯录人员
        this.s_loading(true)
        this.$axios.get(baseURL+'api/jp-HCZZ-AdminWeb-app-ms/addressbook/maillist/findmaillistbystationid/'+this.stationId+'?page='+this.cur+'&pageSize='+this.pageSize)
          .then(res => {
            this.addressPageList = res.data.list;
            this.allDataSum = res.data.total;
            this.allpage = Math.ceil(res.data.total/this.pageSize);
            this.s_loading(false)
          }).catch(err => {
          this.s_loading(false)
          this.s_alert('通讯录数据加载有问题')
          //console.log(err);
        })
      },
      // 当树被展开
      zTreeOnExpand(evt, treeId, treeNode){
        this.setBackSize();
      },
      // 修改树初始化的数据
      switchData(data){
        for(let i = 0; i < data.length; i++){
          if(data[i].hasOwnProperty('pictureUrl') && data[i].pictureUrl){ // 有pictureUrl且有值
            data[i]['icon'] = baseURL                         //运行环境
              + 'api/jp-TIFS-FileCenter-ms/file?businessId='  //微服务地址
              + data[i].pictureUrl;
          }
          else if(data[i].hasOwnProperty('pictureUrl')){ // 有pictureUrl没有值，使用默认图片
            data[i]['icon'] = require('@/../static/img/Policeman.png');
          }
        }
        return data;
      },
      // 修改警员图片background-size属性
      setBackSize(){
        let length = $('.ico_docu').length;
        for(let i = 0; i < length; i++){
          $('.ico_docu')[i].style['background-size'] = "100% 100%";
        }
      },
      // 把树中数据为空的项转化为中文的‘暂无’
      StringIf( treeNode, Str ){
        if(treeNode[Str]){
          this[Str] = treeNode[Str];
        }
        else {
          this[Str] = '暂无';
        }
      },
      // 部门新增下级部门
      btnAddDepartment(){
        this.addDepartmentClose();
        //console.log('btnAddDepartment');
      },
      // 从全部或者归属部门警员中添加到通讯录
      btnAddPolice(str){
        this.AddPoliceModalObj.btnType = str;
        this.addPoliceClose();
        //console.log('btnAddPolice')
      },
      // 通讯录中移除
      deleteRalationBatch(){
        if( this.checkedAddressAry.length <= 0 ){
          this.s_alert('请选择需要移除得警员');
          // alert('请选择需要移除得警员');
          return false;
        }
        this.$axios.post(baseURL+'api/jp-HCZZ-AdminWeb-app-ms/addressbook/policepart/deleteralationbatch/'+this.stationId ,this.checkedAddressAry)
          .then(res => {
            this.s_alert('移除成功');
            // alert('移除成功');
            this.init()
            this.refreshNode();
            // 刷新列表，清空数据
            // this.initTable();
            this.clearCheckedAry = !this.clearCheckedAry;
          }).catch(err => {
            this.s_alert("移除失败")
            // alert("移除失败")
        })
      },
      // 部门修改
      btnUpdataDepartment(){
        this.updateDepartmentClose();
        //console.log('btnUpdataDepartment');
      },
      // 部门删除
      btnDeleteDepartment(){
        let treeObj = $.fn.zTree.getZTreeObj("tree-dep");
        // nodeAry 点击项和其子节点的集合
        let nodeAry = treeObj.transformToArray(this.treeNode);
        if(nodeAry.length > 1){
          this.s_alert('删除部门下面有数据，不能删除！');
          // alert('删除部门下面有数据，不能删除！');
          return false;
        }
        this.$axios({
          url: baseURL+'api/jp-HCZZ-AdminWeb-app-ms/addressbook/part/delete?id='
              + this.updateDepartmentModalObj.id,
          method: 'delete',
          'Content-Type': "application/json;charset=UTF-8"
        })
        .then(res => {
          this.s_alert('删除成功')
          // alert('删除成功')
          this.init();
          this.refreshNode();
        })
        .catch(res => {
          this.s_alert('删除失败')
          // alert('删除失败')
        })
        //console.log('btnDeleteDepartment');
      },
      // 新增部门弹窗关闭操作
      addDepartmentClose(){
        this.AddDepartmentModalObj.isShow = !this.AddDepartmentModalObj.isShow
        if( this.AddDepartmentModalObj.isShow === false ){
          //重新加载表格
          this.init();
        }
      },
      // 新增通讯录人员关闭操作
      addPoliceClose(){
        this.AddPoliceModalObj.isShow = !this.AddPoliceModalObj.isShow;
        if( this.AddPoliceModalObj.isShow === false){
          //页面刷新
          this.init();
          this.refreshNode();

          // 重新加载 tableMate
          // this.initTable();
        }
      },

      // 修改部门弹窗关闭操作
      updateDepartmentClose(){
        this.updateDepartmentModalObj.isShow = !this.updateDepartmentModalObj.isShow;
        if( this.updateDepartmentModalObj.isShow === false ){
          //重新加载表格
          this.init();
          this.refreshNode();
        }
      },
      // 寻找最近的真实部门的id
      searchRealDepartmentId(ary){
        let length = ary.length;
        for(let i = length - 1; i => 0; i-- ){
          if(ary[i]['type'] === 1){
            return ary[i].id;
          }
        }
      },
      // 通讯录被点击的人员
      checkedAryFn(checkedDataAry){
        //从子组件拿到数据
        this.checkedAddressAry = checkedDataAry;
        //console.log(this.checkedAddressAry)
      },
      // 通讯录人员点击修改后事件
      updataAddressFn(data){
        this.updateAddressPeopleModalObj.policeGuid = data.id;
        this.updateAddressPeopleModalObj.policePhone = data.policePhone;
        this.updateAddressPeopleModalObj.policePosition = data.policePosition;
        this.updateAddressPeopleModalObj.policeRadioId = data.policeRadioId;
        this.updateAddressPeopleModalObj.sort = data.sort;
        this.updateAddressPeopleModalObj.secrit = data.secrit;

        this.updateAddressPeopleModalClose();
      },
      // 点击通讯录树上的人员修改操作函数
      updataAddressPeopleFn(){
        let data ={
          "id": this.treeNode.id,
          "policePhone":this.treeNode.policePhone,
          "policePosition": this.treeNode.policePosition,
          "policeRadioId": this.treeNode.policeRadioId,
          "sort": this.treeNode.sort
        }
        this.updataAddressFn(data);
      },
      // 通讯录人员信息修改弹窗
      updateAddressPeopleModalClose(){
        this.updateAddressPeopleModalObj.isShow = !this.updateAddressPeopleModalObj.isShow;
        if( this.updateAddressPeopleModalObj.isShow === false){
          // 重新加载
          this.init();
          this.refreshNode();
        }
      },
      // 通讯录人员分页
      currentChange(current) {
        this.cur = current
        this.axiosAddressPageListFn();
      },
      // 刷新树形结点数据
      refreshNode() {
        let zTree = $.fn.zTree.getZTreeObj("tree-dep");
        let nodes = zTree.getSelectedNodes();
        let type = "refresh";
        if(nodes.length == 0){
          this.s_alert("请先选择一个父节点");
          // alert("请先选择一个父节点");
        }
        for (let i = 0; i < nodes.length; i++){
          zTree.reAsyncChildNodes(nodes[i], type);
          zTree.selectNode(nodes[i]);
        }
      },
      // 异步数据处理
      ajaxDataFilter(treeId, parentNode, responseData) {
        for(let i = 0; i < responseData.length; i++){
          if(parentNode.id === responseData[i].id ){
            responseData.splice(i,1);
          }
        }
        this.$nextTick(()=>{
          this.setBackSize();
        })
        return this.switchData(responseData);
      }
    }
  }
</script>

<style lang="scss" scoped>
  .address-list {
    display: flex;
  }
  .tree-wrap{
    width: 300px;
    height: 100%;
  }
  .div-tree {
    width: 100%;
    height: calc(100% - 40px);
    overflow-y: auto;
    float: left;
    /*&::-webkit-scrollbar {*/
      /*display: none;*/
    /*}*/
  }
  .content-wrap {
    width: calc(100% - 300px);
    height: 100%;
    .click-wrap {
      width: 100%;
      height: 136px;
      position: relative;
      overflow: hidden;
      .title-img {
        position: absolute;
        width: 100%;
        z-index: -1;
      }
      .btn-wrap {
        height: 100%;
        display: flex;
        flex-wrap: wrap;
        flex-align: center;
      }
    }

    .title-wrap {
      float: left;
      .user-wrap {
        width: 100%;
        height:136px;
        text-align: center;
        .user-img-wrap {
          display: inline-block;
          width: 116px;
          height: 116px;
          border-radius: 50%;
          background-color: #002d77;
          .user-img {
            width: 116px;
            height: 116px;
            border-radius: 50%;
            display: inline-block;
          }
        }
        .user-name {
          color: #fff;
          line-height: 20px;
        }
      }
    }
  }
  .details-wrap {
    width: calc(100% - 116px - 48px);
    float: left;
  }
  .details-department{
    display: flex;
    flex-wrap: wrap;
    align-items:center;
    height: 136px;
    .department-wrap {
      flex: 0 0 50%;
      padding-left: 38px;
      font-size: 14px;
      .department-title {
        color: #4fa6ff;
      }
      .department-content {
        color: #fff;
      }
    }
  }
  .ztree li span.button.ico_docu {
    border-radius: 50%;
  }
  .table-mate-height {
    height: calc(100% - 202px);
  }

</style>
